package com.kady.controller.Table;

import com.kady.contant.BeanFactoryConstant;
import com.kady.contant.ExceptionConstant;
import com.kady.contant.MessageConstant;
import com.kady.controller.BaseServlet;
import com.kady.entity.ResultVO;
import com.kady.entity.Table;
import com.kady.factory.BeanFactory;
import com.kady.service.TableService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@WebServlet("/backend/table")
public class TableController extends BaseServlet {

    private TableService tableService = (TableService)BeanFactory.getBean(BeanFactoryConstant.TABLE_SERVICE);

    /**
     * 获取餐桌列表
     */
    public String list (HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String keyword = req.getParameter("keyword");
        List<Table> list= tableService.getTableList(keyword);
        if(keyword!=null){
            req.setAttribute("keyword",keyword.trim());
        }
        req.setAttribute("tables",list);
        return MessageConstant.PREFIX_FORWARD + "/backend/detail/table/table-list.jsp";
    }

    /**
     * 添加餐桌
     */
    public String save (HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, InvocationTargetException, IllegalAccessException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Table table = new Table();
        BeanUtils.populate(table,parameterMap);
        tableService.addTable(table);
        return MessageConstant.PREFIX_FORWARD + "/backend/table?method=list";
    }

    /**
     * 餐桌 预定/退桌
     */
    public Object book (HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        String tableId = req.getParameter("tableId");
        Object obj = tableService.updateStatus(tableId);
        if(obj != null && obj instanceof ResultVO){
            return obj;
        }
        return MessageConstant.PREFIX_FORWARD + "/backend/table?method=list";
    }

    /**
     * 删除餐桌
     */
    public Object delete (HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        String tableId = req.getParameter("tableId");
        /**
         * 判断如果餐桌被预定则不能删除
         */
        Table table =  tableService.getTable(tableId);
        if(table==null){
            return new ResultVO(false,"无法查询到餐桌信息");
        }
        if(table.getStatus()==1){
            return new ResultVO(false,ExceptionConstant.TABLE_HAS_ORDERED);
        }
        tableService.removeTable(tableId);
        return MessageConstant.PREFIX_FORWARD + "/backend/table?method=list";
    }

}
